<template>
  <a-form
    ref="phoneForm"
    :model="userInfo"
    class="login-form"
    layout="vertical"
    @submit="handleSubmit"
  >
    <a-form-item
      field="phone"
      :rules="[
        { required: true, message: $t('login.form.telRequired') },
        {
          match: /^1[3456789]\d{9}$/,
          message: $t('login.form.telInvalid'),
        },
      ]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <!-- TODO: 数字验证 -->
      <a-input
        v-model="userInfo.phone"
        :placeholder="$t('login.form.telPlaceholder')"
        :maxlegth="11"
      >
        <template #prefix>
          <icon-mobile />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      field="captcha_code"
      :rules="[{ required: true, message: $t('login.form.captchaRequired') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input
        v-model="userInfo.captcha_code"
        :placeholder="$t('login.form.captchaPlaceholder')"
        :maxlegth="50"
      >
        <template #prefix>
          <icon-safe />
        </template>
        <template #append>
          <a-button type="text" :loading="smsLoading" @click="getSMSCaptcha">
            <span v-if="countDown === -2" class="captcha-word">{{
              $t('login.form.getCaptcha')
            }}</span>
            <span v-else-if="countDown === -1" class="captcha-word">{{
              $t('login.form.regainCaptcha')
            }}</span>
            <span v-else class="captcha-word">{{ `${countDown}s` }}</span>
          </a-button>
        </template>
      </a-input>
    </a-form-item>
    <a-space :size="16" direction="vertical">
      <div class="login-form-password-actions">
        <a-link @click="changeLogin(LoginMethods.forget)">{{
          $t('login.form.forgetPassword')
        }}</a-link>
      </div>
      <a-button type="primary" html-type="submit" long :loading="loading">
        {{ $t('login.form.login') }}
      </a-button>
    </a-space>
  </a-form>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { useI18n } from 'vue-i18n';
  import { getSms } from '@/api/user';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import type { LoginData } from '@/api/user';
  import { dotToSlash } from '@/utils/index';
  import LoginMethods from '../constant';

  const emit = defineEmits(['changeLogin']);

  const changeLogin = (method: LoginMethods) => {
    emit('changeLogin', method);
  };

  const router = useRouter();
  const { t } = useI18n();
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  const userInfo = reactive({
    phone: '',
    captcha_code: '',
  });

  // TODO: 验证码处理逻辑和忘记密码一致，可抽取成hooks
  // 处理验证码
  const countDown = ref(-2);
  const smsLoading = ref(false);
  const phoneForm = ref<FormInstance>();
  // 存储验证码
  let captchaKey = '';
  const getSMSCaptcha = async () => {
    if (countDown.value >= 0) {
      Message.warning(t('login.form.captchaHoldOn'));
      return;
    }
    const res = await phoneForm.value?.validateField('phone');
    // 仅判断手机号是否校验通过
    if (res) {
      return;
    }
    smsLoading.value = true;
    try {
      const { data } = await getSms(userInfo.phone);
      captchaKey = data;
    } catch (err) {
      // you can report use errorHandler or other
      if (typeof err === 'string') {
        Message.error(err);
      }
    } finally {
      smsLoading.value = false;
      updataCountDown();
    }
  };

  const updataCountDown = () => {
    countDown.value = 60;
    const counter = setInterval(() => {
      if (countDown.value === 0) {
        clearInterval(counter);
        countDown.value = -1;
      } else {
        countDown.value--;
      }
    }, 1000);
  };

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        // eslint-disable-next-line camelcase
        const { phone, captcha_code } = values;
        const data = {
          username: phone,
          // eslint-disable-next-line camelcase
          captcha_code,
          captcha_key: captchaKey,
          grant_type: 'sms_captcha',
        };
        await userStore.login(data as LoginData);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          path: dotToSlash(redirect as string) || '/dashboard',
          query: {
            ...othersQuery,
          },
        });
        Message.success(t('login.form.login.success'));
      } catch (err) {
        Message.error((err as Error).message);
      } finally {
        setLoading(false);
      }
    }
  };
</script>

<script lang="ts">
  export default {
    name: 'TelForm',
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-password-actions {
      display: flex;
      justify-content: space-between;
    }
  }
</style>
